package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 豆油召回工作
class PenguinRecallWork(override val uin: String): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "豆油召回"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询豆油召回信息
            val queryResult = gameApi.queryPenguinRecall()

            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 如果今日召回人数<3，且召回列表不为空
                    if (response.dayCallNum < 3 && response.canBeCall.isNotEmpty()) {
                        // 取第一个豆油的uin
                        val targetUin = response.canBeCall.first().uin
                        val remainingCalls = 3 - response.dayCallNum
                        
                        // 召回3-n次
                        repeat(remainingCalls) {
                            val recallResult = gameApi.recallPenguin(targetUin)
                            recallResult.foldWithApiException(
                                onSuccess = { recallResponse ->
                                    historyManager.addHistory(name, recallResponse.getDescription())
                                },
                                onFailure = { code, msg ->
                                    historyManager.addHistory(name, msg, code)
                                }
                            )
                        }
                    }
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}